package com.gengzp.common.utils;

import jakarta.annotation.PostConstruct;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName RedisUtils
 * @Description redis操作工具类
 * @Author gengzp
 * @Date 2025/5/11 18:41
 */
@Data
@Component
public class RedisUtils {

    private static final Logger logger = LoggerFactory.getLogger(RedisUtils.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static RedisTemplate<String, Object> redisTemplateInstance;

    private RedisUtils() {
    }

    @PostConstruct
    public void init() {
        redisTemplateInstance = redisTemplate;
    }

    // ===================== 通用操作 =====================

    /**
     * 设置过期时间
     *
     * @param key  键
     * @param time 过期时间(秒)
     */
    public static void expire(String key, Long time) {
        redisTemplateInstance.expire(key, time, TimeUnit.SECONDS);
    }

    /**
     * 删除缓存中的key
     *
     * @param key 键
     */
    public static void del(String key) {
        redisTemplateInstance.delete(key);
    }

    // ===================== String操作 =====================

    /**
     * 存入字符串数据, 并指定过期时间
     *
     * @param key   键
     * @param value 值
     * @param time  缓存时间(秒)
     */
    public static void set(String key, String value, Long time) {
        redisTemplateInstance.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

    public static String get(String key) {
        return (String) redisTemplateInstance.opsForValue().get(key);
    }


}
